// Package dbservice
// @Author: zhangdi
// @File: usertool
// @Version: 1.0.0
// @Date: 2023/5/19 10:07
package dbservice

import (
	"ideatools/application/constant"
	"ideatools/application/db/columns"
	"ideatools/application/db/dbdto"
	"ideatools/application/db/entity"
	"ideatools/application/db/repository"
	"ideatools/application/db/sqllite"
	"ideatools/application/dto"
	"ideatools/application/pkgs/mylog"
	"ideatools/application/pkgs/utils"
	"ideatools/application/pkgs/where"
	"strconv"
	"strings"
)

type UserToolService struct {
	repo *repository.UserToolRepository
}

func NewUserToolService() *UserToolService {
	return &UserToolService{
		repo: repository.NewUserToolRepository(sqllite.GetDb()),
	}
}

func (s *UserToolService) GenStruct(DtoUserToolInfo *dbdto.UserToolInfo) {

}

// GetDefaultTool 获取默认应用信息
func (s *UserToolService) GetDefaultTool() *dbdto.UserToolInfo {
	defaultId := Conf().Get(constant.ConfigKeyDefaultToolId)
	if defaultId == "" {
		wheres := where.Format()
		extra := &where.Extra{
			OrderByColumn: columns.UserToolQuickPos,
			OrderByDesc:   true,
			Limit:         1,
			Offset:        0,
		}
		list, _ := s.repo.FindListExtra(wheres, extra)
		if len(list) <= 0 {
			return nil
		}
		info := list[0]
		dtoInfo := &dbdto.UserToolInfo{}
		utils.DtoToEntity(info, dtoInfo)
		return dtoInfo
	} else {
		id, err := strconv.Atoi(defaultId)
		if err != nil {
			return nil
		}
		info := s.FindOneById(uint(id))
		if info == nil {
			return nil
		}
		dtoInfo := &dbdto.UserToolInfo{}
		utils.DtoToEntity(info, dtoInfo)
		return dtoInfo
	}
}

// CreateUserTool 创建一个工具
func (s *UserToolService) CreateUserTool(DtoUserToolCreate *dbdto.UserToolAdd) dto.RespData {
	info, _ := s.repo.FindOneByWhere(where.Format(where.Opt("tool_name", "=", DtoUserToolCreate.ToolName)))
	if info != nil {
		return dto.RespError("应用添加失败，名称【" + DtoUserToolCreate.ToolName + "】已存在")
	}

	err := s.repo.Create(DtoUserToolCreate)
	if err != nil {
		return dto.RespError(err.Error())
	}

	return dto.RespOk("创建完成", DtoUserToolCreate)
}

func (s *UserToolService) UpdateUserTool(DtoUserToolUpdate *dbdto.UserToolUpdate) dto.RespData {
	err := s.repo.Update(DtoUserToolUpdate)
	if err != nil {
		return dto.RespError(err.Error())
	}
	return dto.RespOk("修改完成", DtoUserToolUpdate)
}

func (s *UserToolService) GetListUserTool() dto.RespData {
	wheres := where.Format(where.Opt(columns.UserToolId, ">", 0))
	Extra := &where.Extra{
		OrderByColumn: columns.UserToolQuickPos,
		OrderByDesc:   false,
		Limit:         1000,
	}

	list := s.getToolList(wheres, Extra)
	return dto.RespOk("ok", list)

}

// DelUSerTool 删除
func (s *UserToolService) DelUSerTool(id int) dto.RespData {
	wheres := where.Format(where.Opt("id", "=", id))
	err := s.repo.DeleteByFieldValue(wheres)
	if err != nil {
		return dto.RespError(err.Error())
	}
	return dto.RespOk("ok", nil)

}

func (s *UserToolService) GetUserToolByHotKey(hotkey string) (*dbdto.UserToolInfo, error) {
	wheres := where.Format(where.Opt(columns.UserToolHotKey, "=", hotkey))
	info, err := s.repo.FindOneByWhere(wheres)
	if err != nil {
		return nil, err
	}
	dtoData := &dbdto.UserToolInfo{}
	utils.DtoToEntity(info, dtoData)
	return dtoData, nil
}

func (s *UserToolService) ParsePromptText(toolId uint, clipTexts []string) (error, string) {
	info, err := s.repo.FindOneByWhere(where.Format(where.Opt(columns.UserToolId, "=", toolId)))
	if err != nil {
		return err, ""
	}

	//开始组装
	promptTemplate := info.Prompt
	for i := uint(1); i < info.InputCount+1; i++ {
		replaceStr := constant.PromptPlaceholderPrefix + strconv.FormatInt(int64(i), 10) + constant.PromptPlaceholderSuffix
		promptTemplate = strings.ReplaceAll(promptTemplate, replaceStr, clipTexts[info.InputCount-i])
	}
	return nil, promptTemplate
}

func (s *UserToolService) FindOneById(ToolId uint) *entity.UserTool {
	info, err := s.repo.FindOneByWhere(where.Format(where.Opt(columns.UserToolId, "=", ToolId)))
	if err != nil {
		return nil
	}

	return info
}

// GetQuickTools 获取所有配置了快速启动的tool列表
func (s *UserToolService) GetQuickTools() []*dbdto.UserToolInfo {
	wheres := where.Format(where.Opt(columns.UserToolId, ">", 0))
	Extra := &where.Extra{
		OrderByColumn: columns.UserToolQuickPos,
		OrderByDesc:   false,
		Limit:         28,
	}

	return s.getToolList(wheres, Extra)

}

// 获取工具列表
func (s *UserToolService) getToolList(wheres []*where.Field, Extra *where.Extra) []*dbdto.UserToolInfo {
	List, err := s.repo.FindListExtra(wheres, Extra)
	if err != nil {
		mylog.Error("GetQuickToos() error" + err.Error())
		return nil
	}

	var dtoList []*dbdto.UserToolInfo
	chatDialog := NewChatDialogService()
	for _, tool := range List {
		dtoInfo := &dbdto.UserToolInfo{}
		utils.DtoToEntity(tool, dtoInfo)
		dtoInfo.ChatDialogNum = chatDialog.GetToolChatDialogTotal(tool.Id)
		dtoList = append(dtoList, dtoInfo)
	}
	return dtoList
}

// SetToolQuickPos 设置工具快捷启动面板中的位置
func (s *UserToolService) SetToolQuickPos(ToolId, pos uint) bool {
	err := s.repo.Update(&dbdto.UserToolUpdate{
		QuickPos: pos,
		Id:       ToolId,
	})
	if err != nil {
		mylog.Error("SetToolQuickPos error :" + err.Error())
		return false
	}

	return true
}
